package com.tcm.day03;

/**
 * 两个链表相加
 * https://leetcode.cn/problems/add-two-numbers/description/?envType=problem-list-v2&envId=linked-list
 */
public class Code06_AddTowLinkedList {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        int l1_len = calculateNodeLen(l1);
        int l2_len = calculateNodeLen(l2);

        ListNode l = l1_len >= l2_len ? l1 : l2;
        ListNode s = l == l1 ? l2 : l1;

        int carry = 0;
        ListNode cur = l;
        ListNode lastNext = l;
        while (s != null) {
            int v = s.val + cur.val + carry;
            carry = v / 10;
            v = v % 10;
            cur.val = v;
            lastNext = cur;
            s = s.next;
            cur = cur.next;
        }

        while (cur != null) {
            int v = cur.val + carry;
            carry = v / 10;
            v = v % 10;
            cur.val = v;
            lastNext = cur;
            cur = cur.next;
        }

        if(carry != 0) {
            lastNext.next = new ListNode(1);
        }

        return l;
    }

    public int calculateNodeLen(ListNode node) {
        ListNode cur = node;
        int len = 0;
        while (cur != null) {
            len++;
            cur = cur.next;
        }
        return len;
    }

}
